﻿using System;
using System.Data.Common;
using System.Globalization;
using mojoPortal.Web;
using mojoPortal.Web.Framework;
using mojoPortal.Business;
using Resources;
using eStore.Business;
using eStore.Helpers;

namespace eStore.UI
{

    public partial class AdminDiscountEditPage : mojoBasePage
    {
        private int pageId = -1;
        private int moduleId = -1;
        private Store store;
        private Guid discountGuid = Guid.Empty;
        protected Double timeOffset;
        private TimeZoneInfo timeZone;
        protected CultureInfo currencyCulture = CultureInfo.CurrentCulture;
        protected SiteUser currentUser;

        protected void Page_Load(object sender, EventArgs e)
        {
            LoadParams();

            if (!UserCanEditModule(moduleId))
            {
                SiteUtils.RedirectToAccessDeniedPage();
                return;
            }

            LoadSettings();
            PopulateLabels();
            if (!Page.IsPostBack)
            {
                PopulateControls();
            }

        }



        private void PopulateControls()
        {
            if (discountGuid == Guid.Empty) { return; }

            Discount discount = new Discount(discountGuid);

            txtDiscountCode.Text = discount.DiscountCode;
            txtDescription.Text = discount.Description;

            if (timeZone != null)
            {
                dpBeginDate.Text = DateTimeHelper.LocalizeToCalendar(discount.ValidityStartDate.ToLocalTime(timeZone).ToString("g"));
                if (discount.ValidityEndDate < DateTime.MaxValue)
                {
                    dpEndDate.Text = DateTimeHelper.LocalizeToCalendar(discount.ValidityEndDate.ToLocalTime(timeZone).ToString("g"));
                }

            }
            else
            {
                dpBeginDate.Text = DateTimeHelper.LocalizeToCalendar(discount.ValidityStartDate.AddHours(timeOffset).ToString("g"));
                if (discount.ValidityEndDate < DateTime.MaxValue)
                {
                    dpEndDate.Text = DateTimeHelper.LocalizeToCalendar(discount.ValidityEndDate.AddHours(timeOffset).ToString("g"));
                }
            }

            lblUseCount.Text = discount.UseCount.ToInvariantString();
            txtMaxCount.Text = discount.MaxCount.ToInvariantString();
            txtMinOrderAmount.Text = discount.MinOrderAmount.ToString("c", currencyCulture);
            txtAbsoluteDiscount.Text = discount.AbsoluteDiscount.ToString("c", currencyCulture);
            txtPercentageDiscount.Text = string.Format(currencyCulture, "{0:0%}", discount.PercentageDiscount);
            ckAllowOtherDiscounts.Checked = discount.AllowOtherDiscounts;

        }

        void btnSave_Click(object sender, EventArgs e)
        {
            Page.Validate("Discount");
            if ((!Page.IsValid) || (!ValidateBusinessRules())) { return; }

            Discount discount = new Discount(discountGuid)
                                    {
                                        DiscountCode = txtDiscountCode.Text,
                                        Description = txtDescription.Text,
                                        SiteGuid = siteSettings.SiteGuid,
                                        ModuleGuid = store.ModuleGuid,
                                        StoreGuid = store.Guid,
                                        ProductGuid = Guid.Empty
                                    };

            //TODO: add support for product specific discounts
            if (timeZone != null)
            {
                discount.ValidityStartDate = DateTime.Parse(dpBeginDate.Text).ToUtc(timeZone);
                discount.ValidityEndDate = dpEndDate.Text.Length > 0 ? DateTime.Parse(dpEndDate.Text).ToUtc(timeZone) : DateTime.MaxValue;
            }
            else
            {
                discount.ValidityStartDate = DateTime.Parse(dpBeginDate.Text).AddHours(-timeOffset);
                discount.ValidityEndDate = dpEndDate.Text.Length > 0 ? DateTime.Parse(dpEndDate.Text).AddHours(-timeOffset) : DateTime.MaxValue;
            }

            try
            {
                discount.AbsoluteDiscount = decimal.Parse(txtAbsoluteDiscount.Text, NumberStyles.Currency, currencyCulture);
            }
            catch (FormatException)
            {
                lblError.Text = eStoreResources.DiscountInvalidAmountWarning;
                return;
            }

            decimal percentDiscount;
            try
            {
                percentDiscount = decimal.Parse(txtPercentageDiscount.Text.Replace("%", string.Empty), NumberStyles.Number, currencyCulture);
                percentDiscount = percentDiscount / 100;
            }
            catch (FormatException)
            {
                lblError.Text = eStoreResources.DiscountPercentInvalidWarning;
                return;
            }

            discount.PercentageDiscount = percentDiscount;

            int maxCount;
            int.TryParse(txtMaxCount.Text, NumberStyles.Integer, CultureInfo.InvariantCulture, out maxCount);
            discount.MaxCount = maxCount;

            decimal minOrderAmount;
            decimal.TryParse(txtMinOrderAmount.Text, NumberStyles.Currency, currencyCulture, out minOrderAmount);
            discount.MinOrderAmount = minOrderAmount;
            discount.AllowOtherDiscounts = ckAllowOtherDiscounts.Checked;

            discount.CreatedBy = currentUser.UserGuid;
            discount.LastModBy = currentUser.UserGuid;

            try
            {
                discount.Save();

                string redirectUrl = SiteRoot + "/eStore/AdminDiscountEdit.aspx?pageid="
                    + pageId.ToInvariantString()
                    + "&mid=" + moduleId.ToInvariantString()
                    + "&d=" + discount.DiscountGuid;

                WebUtils.SetupRedirect(this, redirectUrl);
            }
            catch (DbException)
            {
                // most likely a duplicate contstraint
                lblError.Text = eStoreResources.DuplicateCodeException;

            }


        }

        private bool ValidateBusinessRules()
        {


            // check if the discount code is already used
            Discount d = new Discount(store.ModuleGuid, txtDiscountCode.Text);
            if ((d.DiscountGuid != Guid.Empty) && (d.DiscountGuid != discountGuid))
            {
                lblError.Text = eStoreResources.DuplicateCodeException;
                return false;

            }

            return true;
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            if (discountGuid == Guid.Empty) { return; }

            // TODO: should we allow deleting discounts that have been used?
            Discount.Delete(discountGuid);

            string redirectUrl = SiteRoot + "/eStore/AdminDiscounts.aspx?pageid="
                + pageId.ToInvariantString() + "&mid=" + moduleId.ToInvariantString();

            WebUtils.SetupRedirect(this, redirectUrl);


        }




        private void PopulateLabels()
        {
            lnkStoreMenu.Text = eStoreResources.StoreManagerHeading;
            lnkStoreMenu.NavigateUrl = SiteRoot + "/eStore/AdminDashboard.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkAdminDiscount.Text = eStoreResources.DiscountAdministration;
            lnkAdminDiscount.NavigateUrl = SiteRoot + "/eStore/AdminDiscounts.aspx?pageid="
                                       + pageId.ToString(CultureInfo.InvariantCulture)
                                       + "&mid=" + moduleId.ToString(CultureInfo.InvariantCulture);

            lnkCurrentPage.Text = eStoreResources.DiscountEditLink;
            lnkCurrentPage.NavigateUrl = Request.Url.ToString();

            Title = SiteUtils.FormatPageTitle(siteSettings, eStoreResources.DiscountEditLink);
            ltrTitle.Text = eStoreResources.DiscountEditLink;

            btnSave.Text = eStoreResources.DiscountSaveButton;
            btnDelete.Text = eStoreResources.DiscountDeleteButton;

            reqDiscountCode.ErrorMessage = eStoreResources.DiscountCodeRequiredWarning;
            reqDescription.ErrorMessage = eStoreResources.DiscountDescriptionRequiredWarning;
            reqBeginDate.ErrorMessage = eStoreResources.DiscountBeginDateRequiredWarning;
            reqMaxUseCount.ErrorMessage = eStoreResources.DiscountMaxUsesRequiredWarning;
            reqMinOrderAmount.ErrorMessage = eStoreResources.DiscountMinOrderRequiredFieldWarning;
            reqDiscountAmount.ErrorMessage = eStoreResources.DiscountAmountRequiredFieldWarning;
            reqPercentDiscount.ErrorMessage = eStoreResources.DiscountPercentageRequiredFieldWarning;
            lblLeaveBlankForNoEndDate.Text = eStoreResources.DiscountBlankEndDateHelp;
            lblZeroIsUnlimitedUse.Text = eStoreResources.DiscountMaxUseHelp;
            lblZeroMeansNoMinimum.Text = eStoreResources.DiscountMinOrderHelp;

            if (Page.IsPostBack) return;
            dpBeginDate.Text = DateTimeHelper.LocalizeToCalendar(timeZone != null ? DateTime.UtcNow.ToLocalTime(timeZone).ToString("g") : DateTime.UtcNow.AddHours(timeOffset).ToString("g"));
            const decimal zero = 0;
            txtMinOrderAmount.Text = zero.ToString("c", currencyCulture);
            txtAbsoluteDiscount.Text = zero.ToString("c", currencyCulture);
            txtPercentageDiscount.Text = string.Format(currencyCulture, "{0:0%}", zero);
        }

        private void LoadSettings()
        {
            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone = SiteUtils.GetUserTimeZone();
            currencyCulture = ResourceHelper.GetCurrencyCulture(siteSettings.GetCurrency().Code);
            currentUser = SiteUtils.GetCurrentSiteUser();

            if (CurrentPage.ContainsModule(moduleId))
            {
                store = StoreHelper.GetStore();

            }

            btnDelete.Visible = (discountGuid != Guid.Empty);

        }

        private void LoadParams()
        {
            pageId = WebUtils.ParseInt32FromQueryString("pageid", pageId);
            moduleId = WebUtils.ParseInt32FromQueryString("mid", moduleId);
            discountGuid = WebUtils.ParseGuidFromQueryString("d", discountGuid);
        }


        #region OnInit

        protected override void OnPreInit(EventArgs e)
        {
            AllowSkinOverride = true;
            base.OnPreInit(e);
        }

        override protected void OnInit(EventArgs e)
        {
            base.OnInit(e);
            Load += Page_Load;
            btnSave.Click += btnSave_Click;
            btnDelete.Click += btnDelete_Click;
            SuppressMenuSelection();
            SuppressPageMenu();
        }
        #endregion
    }
}
